#include <iostream>
using namespace std;

/*//*********like a value*********** 
class HasPtr{
public:
    HasPtr(const string &s = string()) : ps(new string(s)), i(0) {};
    HasPtr(HasPtr &h) : ps(new string(*h.ps)),i(h.i) {};
    HasPtr &operator=(const HasPtr &);
    ~HasPtr() { delete ps; }

    // private:
    string *ps;
    int i;
};

HasPtr &HasPtr::operator=(const HasPtr &s)
{
    //为了防止自赋值，不能先delete
    auto new_p = new string(*s.ps);
    delete this->ps;
    this->ps = new_p;
    this->i = s.i;
    return *this;
}
*/

/*//*********like a pointer******** */
//类似于shared_ptr
class HasPtr{
public:
    HasPtr(const string &s = string()):ps(new string(s)),i(0),use(new size_t(1)){}
    HasPtr(const HasPtr &p) : ps(p.ps), i(p.i), use(p.use) { 
        ++*use; 
    }
    HasPtr &operator=(const HasPtr& p){
        ++*p.use;
        if(--*use==0){
            delete ps;
            delete use;
        }
        this->ps = p.ps;
        this->i = p.i;
        this->use = p.use;
    }
    ~HasPtr(){
        if(--*use == 0){
            delete ps;
            delete use;
        }
    }
private:
    string *ps;
    int i;
    size_t *use;
};

int main(int argc, char const *argv[])
{
    
    HasPtr h1("aa");
    HasPtr h2;
    h2 = h1;
    
    return 0;
}

